<?php

namespace app\v1\controller;

use support\Request;
use support\Response;
use app\model\BizPayRecordModel;
use app\model\UserModel;
use app\model\CardUserModel;
use app\model\CardModel;
use EasyWeChat\Factory;
use Exception;
use app\model\Util;
use support\Db;
use app\model\BizModel;
use app\model\CardItemModel;
use app\model\PayQrcodeRecordModel;
use app\model\BizAdminModel;
use app\model\RefundRecordModel;

/**
 * 商家支付控制器
 * 
 * 处理云豆支付相关功能
 * 包括云豆余额查询、支付记录创建、云豆支付、微信支付补差价等
 */
class BizPayController {
    /**
     * 获取用户云豆余额
     * 
     * @param Request $request
     * @return Response
     */
    public function balance(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }

            // 检查用户是否已绑定手机号
            if (empty($user['phone'])) {
                throw new Exception('请先绑定手机号');
            }

            // 如果传入user_id，则使用传入的user_id
            $user_id = $request->get('user_id',0);
            if($user_id > 0){
                $user = UserModel::find($user_id);
                if(empty($user)){
                    throw new Exception('用户不存在');
                }
            }

            $biz_id = $request->get('biz_id',0);
            $biz = BizModel::find($biz_id);
            // 普通会员折扣
            $discount = $biz->normal_discount;
            if($user->isVip() && $biz->vip_discount > 0){
                $discount = min($discount, $biz->vip_discount);
            }

            $discount = (float)$discount < 100 ? (float)$discount : false;

            // 获得用户当前卡余额和云豆余额的和
            $userScore = $user->score ?? 0;
            $userCardScore = CardUserModel::where('user_id', $user->id)
            ->where('expired_at','>',time())
            ->sum('score');
            $userTotalScore = $userScore + $userCardScore;

            return json([
                'data' => [
                    'score' => $user->score ?? 0,
                    'phone' => $user->phone,
                    'is_vip' => $user->isVip(),
                    'discount' => $discount,
                    'discount_txt'=>Util::percentToDiscountText($discount),
                    'user_total_score' => $userTotalScore,
                    'un_input_pay_password' => $user->un_input_pay_password
                ],
                'msg' => '获取成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 创建云豆支付
     * 
     * @param Request $request
     * @return Response
     */
    public function create(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }

            // 检查用户是否已绑定手机号
            if (empty($user['phone'])) {
                throw new Exception('请先绑定手机号');
            }

            $userId = $user['id'];
            $input = $request->post();
            
            // 参数验证
            if (empty($input['biz_id'])) {
                throw new Exception('商家ID不能为空');
            }
            
            if (empty($input['pay_price']) || $input['pay_price'] <= 0) {
                throw new Exception('支付金额必须大于0');
            }

            $bizId = $input['biz_id'];
            $payPrice = (float)$input['pay_price'];
            $payMoney = (float)$input['pay_money'] ?? $payPrice;
            $discount = $input['discount'] ?? null;

            

            // 验证折扣参数
            if ($discount !== null) {
                $discount = (float)$discount;
                if ($discount < 0 || $discount > 100) {
                    throw new Exception('折扣比例必须在0-100之间');
                }
            }

            // 获取前端提交的云豆和卡片数据
            $useScore = (float)($input['use_score'] ?? 0); // 云豆余额使用量
            $selectedCards = $input['selected_cards'] ?? []; // 选中的卡片列表

            // 在事务开始前验证商家
            $biz = BizModel::find($bizId);
            if (!$biz) {
                throw new Exception('商家不存在');
            }

            // 查询用户信息获取云豆余额
            $userModel = UserModel::find($userId);
            if (!$userModel) {
                throw new Exception('用户信息不存在');
            }

            $userScore = (float)($userModel->score ?? 0);

            // 验证云豆余额是否足够
            if ($useScore > $userScore) {
                throw new Exception('云豆余额不足');
            }

            // 验证卡片数据
            $validatedCards = [];
            $totalCardScore = 0;
            
            if (!empty($selectedCards)) {
                foreach ($selectedCards as $cardData) {
                    if (empty($cardData['card_id'])) {
                        throw new Exception('用户卡片ID不能为空');
                    }
                    
                    // 前端计算卡片使用的云豆
                    $cardUseScore = (float)($cardData['use_score'] ?? 0);
                    
                    // 查询用户卡片信息
                    $cardUser = CardUserModel::find($cardData['card_id']);
                    
                    if (!$cardUser) {
                        throw new Exception('卡片不存在或已失效');
                    }
                    
                    // 检查卡片是否过期
                    if ($cardUser->expired_at > 0 && $cardUser->expired_at < time()) {
                        throw new Exception('卡片已过期');
                    }
                    
                    $cardScore = (float)($cardUser->score ?? 0);
                    
                    // 验证卡片云豆是否足够
                    if ($cardUseScore > $cardScore) {
                        throw new Exception('卡片云豆不足'.$cardScore.'，实际使用'.$cardUseScore);
                    }
                    
                    $validatedCards[] = [
                        // 'card_user_id' => $cardUser->id,
                        'card_id' => $cardUser->id,
                        'card_name' => $cardData['card_name'] ?? '',
                        'card_score' => $cardScore,
                        'use_score' => $cardUseScore
                    ];
                    
                    $totalCardScore += $cardUseScore;
                }
            }

            // 验证总使用量
            $totalUseScore = $useScore + $totalCardScore;
            if ($totalUseScore > $payMoney) {
                throw new Exception('使用云豆数量超过支付金额');
            }

            if($user->un_input_pay_password == 0 OR $totalUseScore > 200){
                $payPassword = $input['pay_password'] ?? null;
                if(empty($payPassword)){
                    throw new Exception('请输入支付密码');
                }
                
                if($payPassword != $user->pay_password){
                    throw new Exception('支付密码错误');
                }
            }

            // 计算需要微信支付的金额
            $remainMoney = round(($payMoney - $totalUseScore), 2);

            // 开始事务
            Db::beginTransaction();

            try {
                // 准备卡片云豆明细数据
                $cardScoreData = json_encode($validatedCards, JSON_UNESCAPED_UNICODE);

                $payRecord = BizPayRecordModel::add([
                    'user_id' => $userId,
                    'biz_id' => $bizId,
                    'pay_price' => $payPrice,
                    'pay_money' => $payMoney,
                    'pay_status' => 0,
                    'money' => $remainMoney,
                    'score' => $useScore,
                    'card_score' => $totalCardScore,
                    'card_score_data' => $cardScoreData,
                    'discount' => $discount,
                    'phone' => $user->phone
                ]);

                $outTradeNo = 'bp-' . $payRecord->id . '-' . rand(100000, 999999);
                $payRecord->trade_no = $outTradeNo;
                $payRecord->update();

                // 扣除云豆余额
                if ($useScore > 0) {
                    $userModel->score = round($userScore - $useScore, 2);
                    $userModel->save();
                }

                // 扣除卡片云豆
                if (!empty($validatedCards)) {
                    foreach ($validatedCards as $cardData) {
                        // 在事务中复用已查询的卡片信息，避免重复查询
                        $cardUser = CardUserModel::find($cardData['card_id']);
                        if ($cardUser) {
                            $cardUser->score = round($cardUser->score - $cardData['use_score'], 2);
                            $cardUser->save();

                            $cardItem = CardItemModel::find($cardUser->card_item_id);
                            if ($cardItem) {
                                $cardItem->use_score = round($cardItem->use_score + $cardData['use_score'], 2);
                                $cardItem->save();
                            }
                        }
                    }
                }

                // 如果不需要微信支付，直接完成支付
                if ($remainMoney <= 0) {
                    // 更新支付记录状态
                    $payRecord->pay_status = 1;
                    $payRecord->paid_at = time();
                    $payRecord->score_status = 1; // 云豆支付完成
                    $payRecord->save();

                    Db::commit();

                    return json([
                        'data' => [
                            'pay_record_id' => $payRecord->id,
                            'pay_trade_no' => $payRecord->trade_no,
                            'pay_status' => 1,
                            'use_score' => $useScore,
                            'use_card_score' => $totalCardScore,
                            'remain_money' => 0,
                            'message' => '云豆支付成功'
                        ],
                        'msg' => '支付成功',
                        'code' => 1
                    ]);
                } else {
                    if($useScore > 0 || $totalCardScore > 0){
                        $payRecord->score_status = 1;
                        $payRecord->save();
                    }
                    
                    
                    
                    // 获取微信支付配置
                    $wechatConfig = config('wechat.mini_app');
                    $payment = Factory::payment($wechatConfig);
                    $jssdk = $payment->jssdk;

                    $result = $payment->order->unify([
                        'body' => '商家收款-'.$biz->name,
                        'out_trade_no' => $payRecord->trade_no,
                        'total_fee' => (int)($remainMoney * 100), // 转换为分
                        'notify_url' => config('site.site_url') . "/v1/biz-pay/notify",
                        'trade_type' => 'JSAPI',
                        'openid' => $user['open_id'],
                    ]);

                    if ($result['return_code'] !== 'SUCCESS' || $result['result_code'] !== 'SUCCESS') {
                        throw new Exception('微信支付订单创建失败：' . ($result['err_code_des'] ?? '未知错误'));
                    }

                    $wxPayConfig = $jssdk->bridgeConfig($result['prepay_id'], false);

                    // 微信支付创建成功后，提交事务
                    Db::commit();

                    return json([
                        'data' => [
                            'pay_record_id' => $payRecord->id,
                            'pay_status' => 0,
                            'use_score' => $useScore,
                            'use_card_score' => $totalCardScore,
                            'remain_money' => $remainMoney,
                            'wx_pay_config' => $wxPayConfig,
                            'out_trade_no' => $outTradeNo,
                            'message' => '云豆支付部分成功，请完成微信支付'
                        ],
                        'msg' => '请完成微信支付',
                        'code' => 1
                    ]);
                }
            } catch (Exception $e) {
                Db::rollBack();
                throw $e;
            }
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 微信支付回调通知
     * 
     * @param Request $request
     * @return Response
     */
    public function notify(Request $request): Response
    {
        try {
            $config = config('wechat.mini_app');
            $payment = Factory::payment($config);
            
            $response = $payment->handlePaidNotify(function ($message, $fail) {
                // 查询支付记录
                $outTradeNo = $message['out_trade_no'];
                $payRecordId = (int)explode('-', $outTradeNo)[1];
                
                $payRecord = BizPayRecordModel::find($payRecordId);
                if (!$payRecord) {
                    return $fail('支付记录不存在');
                }

                // 检查支付状态
                if ($payRecord->pay_status == 1) {
                    return true; // 已经处理过
                }

                // 验证支付金额
                $expectedAmount = (int)($payRecord->money * 100);
                if ($message['total_fee'] != $expectedAmount) {
                    return $fail('支付金额不匹配');
                }

                // 更新支付记录
                $payRecord->pay_status = 1;
                $payRecord->paid_at = time();
                $payRecord->money_status = 1; // 微信支付完成
                $payRecord->transaction_id = $message['transaction_id'];
                $payRecord->save();

                return true;
            });

            return $response;
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 查询支付状态
     * 
     * @param Request $request
     * @return Response
     */
    public function status(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }

            $userId = $user['id'];
            $payRecordId = $request->get('pay_record_id');

            if (empty($payRecordId)) {
                throw new Exception('支付记录ID不能为空');
            }

            // 查询支付记录
            $payRecord = BizPayRecordModel::where('id', $payRecordId)
                ->where('user_id', $userId)
                ->first();

            if (!$payRecord) {
                throw new Exception('支付记录不存在');
            }

            return json([
                'data' => [
                    'pay_record_id' => $payRecord->id,
                    'pay_status' => $payRecord->pay_status,
                    'pay_price' => $payRecord->pay_price,
                    'pay_money' => $payRecord->pay_money,
                    'use_score' => $payRecord->score,
                    'use_card_score' => $payRecord->card_score,
                    'remain_money' => $payRecord->money,
                    'score_status' => $payRecord->score_status,
                    'money_status' => $payRecord->money_status,
                    'card_score_data' => $payRecord->card_score_data,
                    'discount' => $payRecord->discount,
                    'paid_at' => $payRecord->paid_at,
                    'created_at' => $payRecord->created_at,
                    'pay_trade_no' => $payRecord->trade_no
                ],
                'msg' => '查询成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取用户支付记录列表
     * 
     * @param Request $request
     * @return Response
     */
    public function records(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }

            $userId = $user['id'];
            $page = (int)($request->get('page', 1));
            $limit = (int)($request->get('limit', 10));
            $range = $request->get('range', 'all');
            $keyword = $request->get('keyword', '');
            
            if ($page < 1) $page = 1;
            if ($limit < 1 || $limit > 50) $limit = 10;

            $offset = ($page - 1) * $limit;

            // 查询支付记录，关联商家信息
            $query = BizPayRecordModel::select([
                'biz_pay_record.id',
                'biz_pay_record.pay_price',
                'biz_pay_record.pay_money',
                'biz_pay_record.pay_status',
                'biz_pay_record.score_status',
                'biz_pay_record.money_status',
                'biz_pay_record.paid_at',
                'biz_pay_record.created_at',
                'biz_pay_record.score',
                'biz_pay_record.card_score',
                'biz_pay_record.ping_id',
                'biz_pay_record.money',
                'biz_pay_record.discount',
                'biz.name as biz_name',
                'biz.image as biz_image',
                'biz.avatar as biz_avatar',
                'biz.id as biz_id'
            ])
            ->leftJoin('biz', 'biz_pay_record.biz_id', '=', 'biz.id')
            ->where('biz_pay_record.user_id', $userId)
            ->where('biz_pay_record.hide_at', '=',0)
            ->orderBy('biz_pay_record.created_at', 'desc');

            if($range == 'all'){
                // 所有订单，不需要额外限制
            }else if($range == 'unpay'){
                $query->where('biz_pay_record.pay_status', '=', 0)
                ->where('biz_pay_record.money_status', '=', 0)
                ->where('biz_pay_record.score_status', '=', 0);
            }else if($range == 'some-pay'){
                $query->where('biz_pay_record.pay_status', '=', 0)->where(function($query){
                    $query->where('biz_pay_record.money_status', '=', 1)
                    ->orWhere('biz_pay_record.score_status', '=', 1);
                });
            }else if($range == 'pay'){
                $query->where('biz_pay_record.pay_status', '=', 1);
            }

            if(!empty($keyword)){
                $query->where('biz.name', 'like', '%'.$keyword.'%');
            }

            $records = $query->offset($offset)->limit($limit)->get();

            // 查询总数
            $total = BizPayRecordModel::where('user_id', $userId)->where('hide_at','=',0)->count();

            // 格式化数据
            $formattedRecords = [];
            foreach ($records as $record) {

                // 状态
                $statusLabel = '';
                if($record->pay_status == 1 || $record->score_status == 1 || $record->money_status == 1){
                    $statusLabel = '已支付';
                }else{
                    $statusLabel = '未支付';
                }

                $formattedRecords[] = [
                    'id' => $record->id,
                    'pay_price' => round($record->pay_price,2),
                    'pay_money' => round($record->pay_money,2),
                    'pay_status' => $record->pay_status,
                    'pay_status_text' => $record->pay_status == 1 ? '已支付' : '未支付',
                    'paid_at' => $record->paid_at,
                    'created_at' => $record->created_at,
                    'created_at_text' => date('Y-m-d H:i:s', $record->created_at),
                    'score' => round($record->score,2),
                    'score_status' => $record->score_status,
                    'money_status' => $record->money_status,
                    'ping_id' => $record->ping_id,
                    'card_score' => round($record->card_score,2),
                    'money' => round($record->money,2),
                    'discount' => $record->discount,
                    'biz_name' => $record->biz_name ?? '未知商家',
                    'biz_image' => $record->biz_image ?? '',
                    'biz_id' => $record->biz_id,
                    'total_score' => round(($record->score + $record->card_score),2),
                    'avatar' => Util::pathToUrl($record->biz_avatar),
                    'status_label' => $statusLabel
                ];
            }

            return json([
                'data' => [
                    'list' => $formattedRecords,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit,
                    'has_more' => ($page * $limit) < $total
                ],
                'msg' => '获取成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 补差价支付
     * @param Request $request
     * @return Response
     */
    public function payRemain(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }
            $userId = $user['id'];
            $payRecordId = $request->post('pay_record_id');
            if (empty($payRecordId)) {
                throw new Exception('支付记录ID不能为空');
            }

            // 查找支付记录
            $payRecord = BizPayRecordModel::where('id', $payRecordId)
                ->where('user_id', $userId)
                ->first();
            if (!$payRecord) {
                throw new Exception('支付记录不存在');
            }
            if ($payRecord->money_status == 1) {
                throw new Exception('该订单已补差价，无需重复支付');
            }
            if ($payRecord->money <= 0) {
                throw new Exception('无需补差价');
            }

            // 生成微信支付参数
            $config = config('wechat.mini_app');
            $payment = Factory::payment($config);

            $outTradeNo = 'bizpay-' . $payRecord->id . '-' . time();
            $result = $payment->order->unify([
                'body' => '随心付补差价',
                'out_trade_no' => $outTradeNo,
                'total_fee' => intval($payRecord->money * 100), // 单位：分
                'openid' => $user->open_id,
                'notify_url' => config('site.site_url') . '/v1/biz-pay/notify',
                'trade_type' => 'JSAPI',
            ]);

            if (($result['return_code'] ?? '') !== 'SUCCESS' || ($result['result_code'] ?? '') !== 'SUCCESS') {
                throw new Exception($result['return_msg'] ?? '微信下单失败');
            }

            // 返回前端调起支付参数
            $jssdk = $payment->jssdk;
            $payConfig = $jssdk->bridgeConfig($result['prepay_id'], false);

            return json([
                'data' => [
                    'wx_pay_config' => $payConfig,
                    'pay_record_id' => $payRecord->id,
                    'remain_money' => $payRecord->money
                ],
                'msg' => '补差价下单成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function detail(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }
            $id = $request->get('id');
            if (empty($id)) {
                throw new Exception('支付记录ID不能为空');
            }
            $payRecord = BizPayRecordModel::where('id', $id)->first();
            if (!$payRecord) {
                throw new Exception('支付记录不存在');
            }

            // 获取商家信息
            $biz = BizModel::find($payRecord->biz_id);
            if (!$biz) {
                throw new \Exception('商家信息不存在');
            }

            // 构建返回数据
            $data = [
                'record' => [
                    'id' => $payRecord->id,
                    'pay_price' => round($payRecord->pay_price, 2),
                    'pay_money' => round($payRecord->pay_money, 2),
                    'pay_status' => $payRecord->pay_status,
                    'pay_status_text' => $payRecord->pay_status == 1 ? '已支付' : '未支付',
                    'score_status' => $payRecord->score_status,
                    'money_status' => $payRecord->money_status,
                    'score' => $payRecord->score,
                    'card_score' => $payRecord->card_score,
                    'money' => round($payRecord->money, 2),
                    'card_score_data' => $payRecord->card_score_data,
                    'trade_no' => $payRecord->trade_no,
                    'discount' => $payRecord->discount,
                    'created_at' => date('Y-m-d H:i:s', $payRecord->created_at),
                    'paid_at' => $payRecord->paid_at ? date('Y-m-d H:i:s', $payRecord->paid_at) : ''
                ],
                'biz' => [
                    'id' => $biz->id,
                    'name' => $biz->name,
                    'image' => Util::pathToUrl($biz->image),
                    'phone' => $biz->biz_phone,
                    'address' => $biz->shop_address,
                    'service' => $biz->formatService()
                ],
            ];

            return json([
                 'data' => $data,
                'msg' => '获取成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function startPayFromBiz(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }

            $input = $request->post();
            $payQrcodeRecordId = $input['pay_qrcode_record_id'] ?? null;
            $payPrice = (float)($input['pay_price'] ?? 0);
            $userId = (int)($input['user_id'] ?? 0);
            $bizId = (int)($input['biz_id'] ?? 0);
            
            // 参数验证

            if ($payPrice <= 0) {
                throw new Exception('支付金额必须大于0');
            }
            if ($userId <= 0) {
                throw new Exception('用户ID不能为空');
            }
            if ($bizId <= 0) {
                throw new Exception('商家ID不能为空');
            }

            if($payQrcodeRecordId <= 0){
                throw new Exception('收款码ID不能为空');
            }

            $qrcodeRecord = PayQrcodeRecordModel::find($payQrcodeRecordId);
            if(!$qrcodeRecord){
                throw new Exception('收款码无效');
            }

            if($qrcodeRecord->money > 0){
                throw new Exception('该收款码已收款，请重新生成');
            }

            if($qrcodeRecord->pay_record_id > 0){
                throw new Exception('该收款码已收款，请重新生成');
            }

            if($qrcodeRecord->expired_at < time()){
                throw new Exception('该收款码已过期，请重新生成');
            }

            if($qrcodeRecord->biz_id > 0 && $qrcodeRecord->biz_id != $bizId){
                throw new Exception('该收款码不属于当前商家,请让用户重新生成');
            }

            $userModel = UserModel::find($userId);
            if (!$userModel) {
                throw new Exception('用户信息不存在');
            }

            $biz = BizModel::find($bizId);
            if (!$biz) {
                throw new Exception('商家信息不存在');
            }

            // 计算折扣后的实际支付金额
            $discount = $biz->normal_discount;
            if ($userModel->isVip() && $biz->vip_discount > 0) {
                $discount = min($discount, $biz->vip_discount);
            }
            $discount = (float)$discount < 100 ? (float)$discount : 100;
            
            if($discount > 0 && $discount < 100){
                $payMoney = round($payPrice * $discount / 100, 2);
            }else{
                $payMoney = $payPrice;
            }

            // 获取用户云豆余额
            $userScore = (float)($userModel->score ?? 0);

            // 获取用户所有有效卡片，按过期时间排序（即将过期的优先）
            $userCards = CardUserModel::where('user_id', $userId)
                ->where('score', '>', 0)
                ->where('expired_at','>',time())
                ->orderBy('expired_at', 'asc') // 即将过期的优先
                ->get();

            $totalCardScore = 0;
            $validatedCards = [];
            $remainingPayMoney = $payMoney;

            // 优先使用卡余额支付
            foreach ($userCards as $cardUser) {
                if ($remainingPayMoney <= 0) {
                    break;
                }

                // 检查卡片是否过期
                if ($cardUser->expired_at > 0 && $cardUser->expired_at < time()) {
                    continue; // 跳过已过期的卡片
                }

                $cardScore = (float)($cardUser->score ?? 0);
                if ($cardScore <= 0) {
                    continue;
                }

                // 计算这张卡片需要使用的云豆数量
                $cardUseScore = min($cardScore, $remainingPayMoney);
                
                // 获取卡片名称
                $cardName = '';
                $card = CardModel::find($cardUser->card_id);
                if ($card) {
                    $cardName = $card->name ?? '';
                }
                
                $validatedCards[] = [
                    'card_user_id' => $cardUser->id,
                    'card_id' => $cardUser->card_id,
                    'card_name' => $cardName,
                    'card_score' => $cardScore,
                    'use_score' => $cardUseScore
                ];

                $totalCardScore += $cardUseScore;
                $remainingPayMoney -= $cardUseScore;
            }

            // 如果卡余额不够，使用云豆余额
            $useScore = 0;
            if ($remainingPayMoney > 0) {
                if ($remainingPayMoney > $userScore) {
                    throw new Exception($remainingPayMoney.'用户余额不足，需要支付：' . $payMoney . '元，可用余额：' . ($totalCardScore + $userScore) . '元');
                }
                $useScore = $remainingPayMoney;
            }

            // 开始事务
            Db::beginTransaction();

            try {
                // 准备卡片云豆明细数据
                $cardScoreData = json_encode($validatedCards, JSON_UNESCAPED_UNICODE);

                // 创建支付记录
                $payRecord = BizPayRecordModel::add([
                    'user_id' => $userId,
                    'biz_id' => $bizId,
                    'pay_price' => $payPrice,
                    'pay_money' => $payMoney,
                    'pay_status' => 1, // 直接完成支付
                    'money' => 0, // 不需要微信支付
                    'score' => $useScore,
                    'card_score' => $totalCardScore,
                    'card_score_data' => $cardScoreData,
                    'discount' => $discount,
                    'dir' => 2
                ]);

                // 扣除云豆余额
                if ($useScore > 0) {
                    $userModel->score = round($userScore - $useScore, 2);
                    $userModel->save();
                }

                // 扣除卡片云豆
                if (!empty($validatedCards)) {
                    foreach ($validatedCards as $cardData) {
                        $cardUser = CardUserModel::find($cardData['card_user_id']);
                        if ($cardUser) {
                            $cardUser->score = round($cardUser->score - $cardData['use_score'], 2);
                            $cardUser->use_score = round($cardUser->use_score + $cardData['use_score'], 2);
                            $cardUser->save();

                            // 更新卡片使用记录
                            $cardItem = CardItemModel::find($cardUser->card_item_id);
                            if ($cardItem) {
                                $cardItem->use_score = round($cardItem->use_score + $cardData['use_score'], 2);
                                $cardItem->save();
                            }
                        }
                    }
                }

                // 更新支付记录状态
                $payRecord->pay_status = 1;
                $payRecord->paid_at = time();
                $payRecord->score_status = 1; // 云豆支付完成
                $payRecord->money_status = 0; // 无需微信支付
                $payRecord->save();

                
                $qrcodeRecord->money = $payMoney;
                $qrcodeRecord->pay_record_id = $payRecord->id;
                $qrcodeRecord->save();

                Db::commit();

                return json([
                    'data' => [
                        'pay_record_id' => $payRecord->id,
                        'pay_status' => 1,
                        'pay_price' => $payPrice,
                        'pay_money' => $payMoney,
                        'use_score' => $useScore,
                        'use_card_score' => $totalCardScore,
                        'remain_money' => 0,
                        'discount' => $discount,
                        'message' => '支付成功'
                    ],
                    'msg' => '支付成功',
                    'code' => 1
                ]);

            } catch (Exception $e) {
                Db::rollBack();
                throw $e;
            }

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }


    public function checkBizUsePayQrcodeResult(Request $request) {
        try {
            $input = $request->post();
            $payQrcodeRecordId = $input['pay_qrcode_record_id'] ?? null;

            $payQrcodeRecord = PayQrcodeRecordModel::find($payQrcodeRecordId);
            if(!$payQrcodeRecord){
                throw new Exception('收款码不存在');
            }

            if($payQrcodeRecord->biz_id > 0 && empty($payQrcodeRecord->pay_record_id)){
                $biz = BizModel::find($payQrcodeRecord->biz_id);
                return json(['code'=>1,'msg'=>"商家".$biz->name."已扫码",'data'=>0]);
            }

            if($payQrcodeRecord->pay_record_id > 0){
                return json(['code'=>1,'msg'=>"商家已收款￥".$payQrcodeRecord->money,'data'=>$payQrcodeRecord->money]);
            }

            return json([
                'code'=>1,
                'msg'=>"等待商家扫码",
                'data'=>0
            ]);
        }catch(Exception $e){
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function recordsByBiz(Request $request) {
        try {
            $params = $request->get();
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }

            $page = (int)($request->get('page', 1));
            $limit = (int)($request->get('limit', 10));

            $bizAdmin = BizAdminModel::where('user_id', '=',$user['id'])->first();
            if(!$bizAdmin){
                throw new Exception('用户不是商家管理员');
            }
            
            $biz_id = (int)($bizAdmin->biz_id);

            $offset = ($page - 1) * $limit;

            $query = BizPayRecordModel::query();
            $query->leftJoin('user', 'biz_pay_record.user_id', '=', 'user.id');

            if(!empty($params['phone'])){
                $query->where('biz_pay_record.phone', 'like', "%".$params['phone']."%");
            }
            if(!empty($params['start_date'])){
                $query->where('biz_pay_record.created_at', '>=', strtotime($params['start_date']));
            }
            if(!empty($params['end_date'])){
                $query->where('biz_pay_record.created_at', '<', strtotime($params['end_date'])+86400);
            }

            $query->select([
                'biz_pay_record.id',
                'biz_pay_record.pay_price',
                'biz_pay_record.pay_money',
                'biz_pay_record.pay_status',
                'biz_pay_record.score_status',
                'biz_pay_record.money_status',
                'biz_pay_record.paid_at',
                'biz_pay_record.created_at',
                'biz_pay_record.score',
                'biz_pay_record.card_score',
                'biz_pay_record.ping_id',
                'biz_pay_record.money',
                'biz_pay_record.discount',
                'biz_pay_record.phone',
                'biz_pay_record.refund_status',
                'biz_pay_record.bill_id'
            ])
            ->where('biz_pay_record.biz_id', '=',$biz_id)
            ->where('biz_pay_record.pay_status', '=',1)
            ->orderBy('biz_pay_record.created_at', 'desc');
            

            $records = $query->offset($offset)->limit($limit)->get();

            foreach($records as &$record){
                $record['user_phone'] = empty($record['phone']) ? '-' : mb_substr($record['phone'],0,3).'****'.mb_substr($record['phone'],-4);
                $record['created_at'] = date('Y-m-d H:i:s',$record['created_at']);
                $record['paid_at_txt'] = date('Y-m-d H:i:s',$record['paid_at']);

                $record['pay_price'] = round($record['pay_price'],2);
                $record['pay_money'] = round($record['pay_money'],2);

                $record['can_refund'] = (time() - $record->paid_at) <= 3600*8;
            }

            $total = BizPayRecordModel::where('biz_pay_record.user_id', $user['id'])
            ->where('biz_pay_record.biz_id', $biz_id)
            ->count();

            return json([
                'data' => [
                    'records' => $records,
                    'total' => $total
                ],
                'msg' => '获取商家支付记录成功',
                'code' => 1
            ]);

        }catch(Exception $e){
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    // refund-by-biz
    public function refundByBiz(Request $request) {
        try {
            $user = $request->userLogin;
            $input = $request->post();
            $id = $input['id'] ?? null;

            $bizAdmin = BizAdminModel::where('user_id', '=',$user['id'])->first();
            if(!$bizAdmin){
                throw new Exception('用户不是商家管理员');
            }

            $payRecord = BizPayRecordModel::find($id);
            if(!$payRecord){
                throw new Exception('支付记录不存在');
            }

            if($payRecord->biz_id != $bizAdmin->biz_id){
                throw new Exception('支付记录不属于当前商家');
            }

            if($payRecord->pay_status != 1){
                throw new Exception('支付记录未支付');
            }

            if($payRecord->refund_status > 0){
                throw new Exception('支付记录已有退款操作，无法重复操作');
            }

            $refundRecord = new RefundRecordModel();
            $refundRecord->type = 'pay';
            $refundRecord->item_id = $payRecord->id;
            $refundRecord->refund_amount = $payRecord->pay_money;
            $refundRecord->refund_at = 0;
            $refundRecord->status = 'doing';
            $refundRecord->created_at = time();
            $refundRecord->updated_at = time();
            $refundRecord->save();

            $payRecord->refund_status = 1;
            $payRecord->refund_record_id = $refundRecord->id;
            $payRecord->refund_at = time();
            $payRecord->save();

            return json([
                'data' => null,
                'msg' => '退款发起成功',
                'code' => 1
            ]);

        }catch(Exception $e){
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function doHide(Request $request) {
        try {
            $user = $request->userLogin;
            $input = $request->post();
            $id = $input['id'] ?? null;

            $payRecord = BizPayRecordModel::find($id);
            if(!$payRecord){
                throw new Exception('支付记录不存在');
            }

            if($payRecord->hide_at > 0){
                throw new Exception('支付记录已隐藏');
            }

            if($payRecord->user_id != $user['id']){
                throw new Exception('支付记录不属于当前用户');
            }
            
            $payRecord->hide_at = time();
            $payRecord->save();

            return json([
                'data' => null,
                'msg' => '隐藏成功',
                'code' => 1
            ]);
        }
        catch(Exception $e){
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
}